﻿using Dapper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EWechatNotice
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btn_SaveConfig_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(this.txt_CorpId.Text))
            {
                MessageBox.Show("请填写CorpId");
                return;
            }
            else
            {
                WechatConfigModel._ConfigModel.CorpId = this.txt_CorpId.Text;
            }
            if(string.IsNullOrEmpty(this.txt_CorpSecret.Text))
            {
                MessageBox.Show("请填写CorpSecret");
                return;
            }
            else
            {
                WechatConfigModel._ConfigModel.CorpSecret = this.txt_CorpSecret.Text;
            }
            if (string.IsNullOrEmpty(this.txt_AppId.Text))
            {
                MessageBox.Show("请填写AppId");
                return;
            }
            else
            {
                WechatConfigModel._ConfigModel.AppId = this.txt_AppId.Text;
            }
            if(string.IsNullOrEmpty(this.txt_IpAddress.Text))
            {
                MessageBox.Show("请填写数据库IP地址");
                return;
            }
            else
            {
                DataBaseConfigModel._DataBaseConfigModel.IpAddress = this.txt_IpAddress.Text;
            }
            if (string.IsNullOrEmpty(this.txt_Account.Text))
            {
                MessageBox.Show("请填写数据库账户");
                return;
            }
            else
            {
                DataBaseConfigModel._DataBaseConfigModel.Account = this.txt_Account.Text;
            }
            if (string.IsNullOrEmpty(this.txt_PassWord.Text))
            {
                MessageBox.Show("请填写数据库密码");
                return;
            }
            else
            {
                DataBaseConfigModel._DataBaseConfigModel.Password = this.txt_PassWord.Text;
            }
            if (string.IsNullOrEmpty(this.txt_CircleMin.Text))
            {
                MessageBox.Show("请填写轮询时间");
                return;
            }
            else
            {
                OtherConfigModel._OtherConfigModel.CycleMinute = this.txt_CircleMin.Text;
            }
            if (string.IsNullOrEmpty(this.txt_sql.Text))
            {
                MessageBox.Show("请填写数据sql");
                return;
            }
            else
            {
                OtherConfigModel._OtherConfigModel.SqlStr = this.txt_sql.Text;
            }
            if(string.IsNullOrEmpty(this.txt_DbName.Text))
            {
                MessageBox.Show("请填写数据库名称");
                return;
            }
            else
            {
                DataBaseConfigModel._DataBaseConfigModel.DataBaseName = this.txt_DbName.Text;
            }
            if(string.IsNullOrEmpty(this.txt_BackSQL.Text))
            {
                MessageBox.Show("请填写回写的sql");
                return;
            }
            else
            {
                OtherConfigModel._OtherConfigModel.BackSQL = this.txt_BackSQL.Text;
            }
            //if(string.IsNullOrEmpty(this.txtBackValue.Text))
            //{
            //    MessageBox.Show("请填写回写的值");
            //    return;
            //}
            //else
            //{
            //    OtherConfigModel._OtherConfigModel.BackFieldValue = this.txtBackValue.Text;
            //}
            //if (string.IsNullOrEmpty(this.txt_BackField.Text))
            //{
            //    MessageBox.Show("请填写回写的字段");
            //    return;
            //}
            //else
            //{
            //    OtherConfigModel._OtherConfigModel.BackField = this.txt_BackField.Text;
            //}
            //if (string.IsNullOrEmpty(this.txt_BasisField.Text))
            //{
            //    MessageBox.Show("请填写回写依据的字段");
            //    return;
            //}
            //else
            //{
            //    OtherConfigModel._OtherConfigModel.BasisField = this.txt_BasisField.Text;
            //}
            //if (string.IsNullOrEmpty(this.txt_BackTable.Text))
            //{
            //    MessageBox.Show("请填写回写的表");
            //    return;
            //}
            //else
            //{
            //    OtherConfigModel._OtherConfigModel.BackTable = this.txt_BackTable.Text;
            //}


            ConfigModel config = new ConfigModel();
            config.DataBaseConfig = DataBaseConfigModel._DataBaseConfigModel;
            config.WechatConfig = WechatConfigModel._ConfigModel;
            config.OtherConfig = OtherConfigModel._OtherConfigModel;

            string configStr = config.ToJson();

            //把txt清空
            FileStream stream = File.Open(Application.StartupPath + "\\cusconfig.txt", FileMode.OpenOrCreate, FileAccess.Write);
            stream.Seek(0, SeekOrigin.Begin);
            stream.SetLength(0);
            stream.Close();
            //向txt里面追加信息
            StreamWriter sw = new StreamWriter(Application.StartupPath + "\\cusconfig.txt", true, Encoding.GetEncoding("gb2312"));
            sw.WriteLine(configStr);
            sw.Flush();
            sw.Close();
            MessageBox.Show("保存成功，下次启动将会自动加载以上信息");

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            //WechatConfigModel._ConfigModel = new WechatConfigModel();
            //DataBaseConfigModel._DataBaseConfigModel = new DataBaseConfigModel();
            //OtherConfigModel._OtherConfigModel = new OtherConfigModel();

            LoadInterface();
            
        }
        
        private void LoadInterface()
        {
            string str;
            StreamReader sr = new StreamReader(Application.StartupPath + "\\cusconfig.txt", Encoding.GetEncoding("gb2312"));
            str = sr.ReadLine().ToString();
            sr.Close();

            ConfigModel config = str.ToObject<ConfigModel>();
            if (config.DataBaseConfig != null)
            {
                this.txt_IpAddress.Text = config.DataBaseConfig.IpAddress;
                this.txt_Account.Text = config.DataBaseConfig.Account;
                this.txt_PassWord.Text = config.DataBaseConfig.Password;
                this.txt_DbName.Text = config.DataBaseConfig.DataBaseName;
            }
            if (config.WechatConfig != null)
            {
                this.txt_AppId.Text = config.WechatConfig.AppId;
                this.txt_CorpId.Text = config.WechatConfig.CorpId;
                this.txt_CorpSecret.Text = config.WechatConfig.CorpSecret;
                PublicParam.CorpId= config.WechatConfig.CorpId;
                PublicParam.CorpSecret= config.WechatConfig.CorpSecret;
                PublicParam.AppId = config.WechatConfig.AppId;
            }
            if (config.OtherConfig != null)
            {
                this.txt_CircleMin.Text = config.OtherConfig.CycleMinute;
                this.txt_sql.Text = config.OtherConfig.SqlStr;
                this.txtBackValue.Text = config.OtherConfig.BackFieldValue;
                this.txt_BackField.Text = config.OtherConfig.BackField;
                this.txt_BasisField.Text = config.OtherConfig.BasisField;
                this.txt_BackTable.Text = config.OtherConfig.BackTable;
                this.txt_BackSQL.Text = config.OtherConfig.BackSQL;
            }
            this.btn_Pause.Enabled = false;
        }
        private static bool IsStart = false;
        private static bool IsPause = false;
        private static string sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
        private void btn_StartService_Click(object sender, EventArgs e)
        {
            if (IsStart)
            {
                IsPause = false;
                return;
            }
            //获取微信token
            string connStr = "Server="+this.txt_IpAddress.Text + ";Database="+this.txt_DbName.Text + ";User id="+this.txt_Account.Text+ ";password="+this.txt_PassWord.Text;
            DapperHelper.Instance.EditConnection(connStr);
            this.lab_Status.Text = "运行中";
            IsStart = true;
            this.btn_StartService.Enabled = false;
            this.btn_Pause.Enabled = true;

            Thread dataThread = new Thread(delegate () {
                while (true)
                {
                    if (IsPause==false)
                    {
                        List<SendDataModel> List = new List<SendDataModel>();
                        using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                        {
                            string sql = this.txt_sql.Text;
                            List = conn.Query<SendDataModel>(sql).ToList();
                        }
                        if(List.Count>0)
                        {
                            foreach(var d in List)
                            {
                                if (WechatToken.IsTimeOut())
                                {
                                    WechatToken.GetNewToken();
                                }
                                CorpSendText sendtext = new CorpSendText(d.MessageStr);
                                sendtext.touser = d.UserId;
                                sendtext.agentid = this.txt_AppId.Text;
                                var data = new HttpPostRequest().Send(sendMessageUrl.Replace("ACCESS_TOKEN", WechatToken._WechatToken.access_token), sendtext.ToJson());

                                this.txtResult.Text = data.ToString();
                                LogHelper.Info(data.ToString()+"报文:"+ sendtext.ToJson().ToString());
                                //string returnsql = string.Format(" update {0} set {1}='{2}' where {3}='{4}' ",this.txt_BackTable.Text,this.txt_BackField.Text,this.txtBackValue.Text,this.txt_BasisField.Text,d.Id);

                                string returnsql = this.txt_BackSQL.Text.Replace("{Id}", d.Id);

                                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                                {
                                    conn.Execute(returnsql);
                                }
                            }
                            
                        }
                        else
                        {
                            LogHelper.Info("本次循环没有数据");
                        }
                    }
                    Thread.Sleep(Convert.ToInt32(this.txt_CircleMin.Text)*60*1000);
                }
            });

            dataThread.IsBackground = true;
            dataThread.Name = "123";
            dataThread.Start();
        }

        private void btn_Pause_Click(object sender, EventArgs e)
        {
            IsPause = true;
            this.lab_Status.Text = "暂停";
            this.btn_StartService.Enabled = true;
            this.btn_Pause.Enabled = false;
        }
    }
}
